package com.leyou.trade.service.impl;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addCart(CartItem cartItem) {
        handleUpdateItem(cartItem);
        cartRepository.save(cartItem);
    }

    @Override
    public List<CartItem> findCarts() {
        UserDetail user = UserContext.getUser();
        List<CartItem> cartList = cartRepository.findByUserId(user.getId(), Sort.by("updateTime"));
        return cartList;
    }

    @Override
    public void updateNumber(Long skuId, Integer num) {
/*        String id = createId(skuId);
        Optional<CartItem> optional = cartRepository.findById(id);
        if(optional.isPresent()){
            CartItem cartItem = optional.get();
            cartItem.setNum(num);
            cartRepository.save(cartItem);
        }*///访问数据库两次，数据库压力大，使用笔记的方法访问数据库一次
        mongoTemplate.update(CartItem.class)
                .matching(Query.query(Criteria.where("_id").is(createId(skuId))))
                .apply(Update.update("num",num).currentDate("updateTime"))
                .first();
    }

    @Override
    public void deleteCart(Long skuId) {
        String id = createId(skuId);
        cartRepository.deleteById(id);
    }

    @Override
    public void saveAll(List<CartItem> cartItems) {
        List<CartItem> itemList = cartItems.stream()
                .map(cartItem -> handleUpdateItem(cartItem))
                .collect(Collectors.toList());
        cartRepository.saveAll(itemList);
    }

    private String createId(Long skuId){
        return String.format("u%ds%d", UserContext.getUser().getId(), skuId);
    }

    private CartItem handleUpdateItem(CartItem cartItem){
        Long userId = UserContext.getUser().getId();
        String id = createId(cartItem.getSkuId());
        Optional<CartItem> optional = cartRepository.findById(id);
        if(optional.isPresent()){
            Integer num = cartItem.getNum();
            cartItem = optional.get();
            cartItem.setNum(num+cartItem.getNum());
        }
        cartItem.setId(id);
        cartItem.setUserId(userId);
        cartItem.setUpdateTime(new Date());
        return cartItem;
    }
}
